<template>
    <div>
      <div class="addcate">
          <span>母婴资讯列表</span>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="addcategoryFn">新增资讯</el-button>
      </div>
      <!-- 编辑的对话框 -->
      <el-dialog title="新增母婴资讯" :visible.sync="dialogFormVisible" width="500px" @close="dialogCloseFN" fullscreen>
            <el-form :model="articleForm" :rules="articleRules" ref="addref">
              <el-form-item label="文章标题" :label-width="formLabelWidth" prop="title">
                <el-input v-model="articleForm.title" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="文章内容" :label-width="formLabelWidth" prop="content">
                <mavonEditor
                v-model="articleForm.content"
                ref="md"
                @change="change"
                style="min-height: 600px" />
              </el-form-item>
              <el-form-item label="文章封面" :label-width="formLabelWidth" prop="publish_img">
                <el-checkbox-group v-model="articleForm.publish_img" v-show="false"></el-checkbox-group>
                <img src="../../../assets/images/addPicture.jpg" alt="" ref="imgRef" class="img-article">
                <input type="file" style="display:none" ref="iptRef" accept="image/*" @change="oncoverChangeFN">
                <br>
                <el-button size="mini" type="text" @click="clickipt">上传图片</el-button>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button @click="confimFn" type="primary">确 定</el-button>
            </div>
          </el-dialog>
      <el-table
          :data="currentarticleList"
          border
          style="width:100%">
          <el-table-column
          fixed
          type="index"
          label="序号"
          width="50">
          </el-table-column>
          <el-table-column
          fixed
          prop="title"
          label="文章标题"
          width="200">
          </el-table-column>
          <el-table-column
          prop="publish_img"
          label="文章封面"
          width="200">
          <template slot-scope="scope">
            <!-- <img src="../../../assets/images/addPicture.jpg" alt="" ref="imgRef" class="img-article"> -->
            <img :src="scope.row.publish_img" alt="" ref="imgRef" class="img-article">
          </template>
        </el-table-column>
        <el-table-column
          prop="publish_time"
          label="发布时间"
          width="200">
        </el-table-column>
          <el-table-column
              label="操作"
              width="200">
              <template slot-scope="scope">
                  <el-button
                  size="mini"
                  @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
          </el-table-column>
      </el-table>
      <el-pagination
        v-if="articleForm.length > 10"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="currentPage"
        :total="articleList.length"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </template>

<script>
import { getarticleAPI, deletearticleAPI, changearticleAPI, publisharticleAPI } from '@/api'
import imgUrl from '../../../assets/images/addPicture.jpg'
import { mapMutations } from 'vuex'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
// import moment from 'moment'
export default {
  name: 'article-manage',
  components: {
    mavonEditor
  },
  data () {
    return {
      articleList: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      formLabelWidth: '120px',
      articleRules: {
        title: [
          { required: true, message: '请输入资讯标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入资讯内容', trigger: 'blur' }
        ],
        publish_img: [
          { required: true, message: '请上传封面', trigger: 'change' }
        ]
      },
      dialogFormVisible: false,
      // isEdit 修改true/添加false
      isEdit: false,
      editId: '',
      // 文章表单
      articleForm: {
        title: '',
        content: '',
        publish_img: '',
        publish_time: ''
      },
      html: ''
    }
  },
  computed: {
    totalPages () {
      return Math.ceil(this.articleList.length / this.pageSize) // 总页数
    },
    currentarticleList () {
      const startIndex = (this.currentPage - 1) * this.pageSize
      const endIndex = startIndex + this.pageSize
      return this.articleList.slice(startIndex, endIndex)
    }
  },
  created () {
    this.getarticleList()
  },
  methods: {
    ...mapMutations(['getCategory']),
    // 重置表单
    dialogCloseFN () {
      this.$refs.addref.resetFields()
      this.articleForm.publish_img = null
      this.$refs.imgRef.setAttribute('src', imgUrl)

      // console.log(1)
    },
    // 获取资讯信息
    async getarticleList () {
      const { data } = await getarticleAPI()
      this.articleList = data.data
    },
    // 添加资讯
    addcategoryFn () {
      this.isEdit = false
      this.dialogFormVisible = true
    },
    // 修改资讯 - 将isEdit修改为true （修改） 传入id打开对话框
    handleEdit (row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogFormVisible = true
      // 用户点击修改 - 则将下面的属性赋值为初始值
      this.$nextTick(() => {
        this.articleForm.title = row.title
        this.articleForm.content = row.content
        this.articleForm.publish_img = row.publish_img
        this.$refs.imgRef.setAttribute('src', row.publish_img)
      })
    },
    // 确定添加分类
    confimFn () {
      this.$refs.addref.validate(async valid => {
        // const time1 = new Date().getTime
        // const time = moment(time1).format('YYYY-MM-DD HH:mm:ss')
        const now = new Date()
        const year = now.getFullYear()
        const month = now.getMonth() + 1
        const day = now.getDate()
        const hours = now.getHours()
        const minutes = now.getMinutes()
        const time = `${year}-${month}-${day} ${hours}:${minutes}`
        const formattime = time.toString()
        if (valid) {
          if (this.isEdit) {
            this.articleForm.id = this.editId
            this.articleForm.publish_time = formattime
            this.articleForm.content = this.html
            const { data } = await changearticleAPI(this.articleForm)
            if (data.status !== 0) return this.$message.error(data.message)
            this.$message.success(data.message)
          } else {
            this.articleForm.publish_time = formattime
            this.articleForm.content = this.html
            console.log(this.articleForm.publish_time)
            const { data } = await publisharticleAPI(this.articleForm)
            if (data.status !== 0) return this.$message.error(data.message)
            this.$message.success(data.message)
          }
          this.getarticleList()
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    // 删除资讯
    async handleDelete (row) {
      const { id } = row
      const { data } = await deletearticleAPI(id)
      if (data.status !== 0) return this.$message.error(data.message)
      this.$message.success(data.message)
      this.getarticleList()
    },
    change (value, render) {
      this.html = render
    },
    clickipt () {
      this.$refs.iptRef.click()
    },
    oncoverChangeFN (e) {
      const file = e.target.files
      if (file.length === 0) {
        this.articleForm.publish_img = null
        this.$refs.imgRef.setAttribute('src', imgUrl)
      } else {
        const fr = new FileReader()
        fr.readAsDataURL(file[0])
        fr.onload = (e) => {
          this.$refs.imgRef.setAttribute('src', e.target.result)
          this.articleForm.publish_img = e.target.result
        }
      }
    },
    handleCurrentChange (newPage) {
      this.currentPage = newPage
    }
  }
}
</script>

  <style scoped>
     .addcate{
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
     }
     .el-input{
      width:100%;
     }
     .el-table {
      border-radius: 8px;
    }
    .el-button {
      border-radius: 8px;
    }
    ::v-deep .el-input__inner{
      height: 2.5em;
      border-radius: 14px;
    }
    .img-article {
      width: 150px;
      height: 150px;
    }
  </style>
